package com.ccc.ka.controller;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ccc.ka.entity.Records;
import com.ccc.ka.service.IRecordsService;
import com.ccc.ka.util.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * 
 * @author ccc
 * @since 2023-02-28
 */
@RestController
@RequestMapping("/records")
public class RecordsController extends BaseController {

@Autowired
private IRecordsService recordsService;
@Autowired
private KASequence sequence;
@PostMapping("/saveRecords")
public KAResponse saveRecords(Records records) throws KAException {
    //1个人单据编号：RC+个人ID+YYYYMMDD00，2团队单据编号：RC+团队ID+YYYYMMDD000
    String rc = "";
    if("1".equals(records.getRcRecordType())){
        rc = sequence.getSeqWithMiddleDate("RC", String.valueOf(records.getRcIdRel()), new Date(), 2);
    }else if("2".equals(records.getRcRecordType())){
        rc = sequence.getSeqWithMiddleDate("RC", String.valueOf(records.getRcIdRel()), new Date(), 3);
    }
    records.setId(UUID());
    records.setRcId(rc);
    records.setCrtTm(LocalDateTimeUtil.now());
    return success(recordsService.save(records));
}

@DeleteMapping("/delRecords")
public KAResponse delRecords(Records records){
    return success(recordsService.removeById(records));
}

@PutMapping("/updRecords")
public KAResponse putRecords(Records records){
    records.setUpdTm(LocalDateTimeUtil.now());
    return success(recordsService.updateById(records));
}

@GetMapping("/getRecords")
public KAResponse getRecords(String id){
    return success(recordsService.getById(id));
}

@GetMapping("/getRecordsPage")
public KAResponse getRecordsPage(Page page, Records records){
    //查询，判断支出，数据取负
    String inOrOutType = records.getInOrOutType();
    if(StringUtils.isNotBlank(inOrOutType) && "out".equals(inOrOutType)){
        Double minAmount = records.getMinAmount();
        Double maxAmount = records.getMaxAmount();
        records.setMaxAmount(KAUtils.exchangeMinus(minAmount));
        records.setMinAmount(KAUtils.exchangeMinus(maxAmount));
    }
    return success(recordsService.getRecordsPage(page, records));
}

@GetMapping("/getRecordsTotalForUserOrTeam")
public KAResponse getRecordsTotalForUserOrTeam(Records records){
    return success(recordsService.getRecordsTotalForUserOrTeam(records));
}

}
